<template>
	<view>
		<u-navbar title=" " leftIcon="bell" placeholder :bgColor="bgColor" :border="false"></u-navbar>

		<view class="user">
			<view class="avatar-wrap">
				<image :src="userInfo.avatar || defaultAvatar" mode="aspectFill" class="avatar" />
			</view>
			<view class="user-info">
				<view class="oneline">
					<view class="username">
						{{ userInfo.userName.length > 10 ? userInfo.userName.slice(0, 10) + '...' : userInfo.userName || '未登录' }}
					</view>
				</view>
				<view class="userid">身份:
					{{ userInfo.bindType === "0" ? '考研' : (userInfo.bindType === "1" ? '考公/考编' : '-') }}
				</view>
				<view class="userid">用户ID: {{ userInfo.id || '-' }}</view>
				<view class="user-days">入住天数: {{ userInfo.joinDays || 0 }}</view>
			</view>
		</view>

		<view class="balance-wrap">
			<view class="balance-item" v-for="(item, index) in balanceList" :key="index">
				<view class="number">{{ item.value }}</view>
				<view class="text">{{ item.label }}</view>
			</view>
		</view>

		<view class="notice-wrap">
			系统最新公告: {{noticeText || '无公告' }}
		</view>

		<view class="grid-wrap">
			<view class="grid-item" v-for="(item, index) in gridList" :key="index" @click="onGridItemClick(item)">
				<image class=" img" :src="item.icon" mode="widthFix">
				</image>
				<view class="name">{{ item.name }}</view>
			</view>
		</view>

		<!-- 身份编辑弹窗 -->
		<tn-modal v-model="showEditIdentityModal" title="编辑身份" :custom="true">
			<view class="modal-body">
				<view class="form-item">
					<text class="label">用户名：</text>
					<input v-model="editUserName" class="input" placeholder="请输入用户名" maxlength="20" type="text" />
				</view>

				<!-- 身份选择 -->
				<view class="form-item">
					<text class="label">身份选择：</text>
					<radio-group @change="onBindTypeChange">
					  <label v-for="option in identityOptions" :key="option.value" class="radio-label">
					    <radio 
					      :value="option.value" 
					      :checked="editBindType === option.value" 
					      name="identity"
					    />
					    <text>{{ option.label }}</text>
					  </label>
					</radio-group>
				</view>

				<view class="modal-footer">
					<button class="btn cancel" @click="showEditIdentityModal = false">取消</button>
					<button class="btn confirm" @click="submitIdentity">保存</button>
				</view>
			</view>
		</tn-modal>


		<custom-tab-bar :currentIndex="4"></custom-tab-bar>
	</view>
</template>

<script>
	import myRequest from '@/api/my.js';

	export default {
		data() {
			return {

				noticeText: '📢 系统将于8月5日23:00进行维护',

				bgColor: 'transparent',
				defaultAvatar: '../../static/avatar/default.png',
				userInfo: {
					id: '', // 用户id
					userName: '', // 用户名
					bindType: '', // 用户绑定身份
					joinDays: '',
					avatar: 'https://img.hellozm.com/production/design/1691387775794-CcwM45mOlBByR79X.png', // 头像
					drawCurrency: "", // 抽币
				},
				balanceList: [], // ✅ 初始化为空，接口后动态设置
				gridList: [{
						name: '抽币记录',
						icon: '../../static/icon/choubijilu.png'
					},
					// {
					// 	name: '收藏夹',
					// 	icon: '../../static/icon/shoucangjia.png'
					// },
					{
						name: '学习记录',
						icon: '../../static/icon/xuexijilu.png'
					},
					{
						name: '重点标记',
						icon: '../../static/icon/zhongdianbiaoji.png'
					},
					{
						name: '身份编辑',
						icon: '../../static/icon/shenfenxiugai.png'
					},
					{
						name: '消息通知',
						icon: '../../static/icon/xiaoxitongzhi.png'
					},
					{
						name: '笔记模版',
						icon: '../../static/icon/moban.png'
					},
				],

				// 身份编辑
				showEditIdentityModal: false, // 控制身份编辑弹窗显示隐藏
				editBindType: '', // 当前选中的身份值，初始化为空或用户当前身份
				editUserName: '',
				identityOptions: [ // 身份选项
					{
						label: '考研',
						value: '0'
					},
					{
						label: '考公/考编',
						value: '1'
					},
				],
			};
		},
		async onLoad() {
			await this.refreshUserData();
		},

		async onShow() {
			await this.refreshUserData();
		},

		methods: {
			
			// 用户类型选择
			onBindTypeChange(e) {
			    // 小程序端这里取的是字符串
			    this.editBindType = e.detail.value;
			},

			// 点击图标的事件
			async onGridItemClick(item) {
				// 你可以在这里执行跳转、弹窗等逻辑
				if (item.name === "笔记模版") {
					this.downloadTemplate();
				} else if (item.name === "身份编辑") {
					await this.onEditIdentityClick();
				} else {
					uni.showToast({
						title: 'Tigo队长在加快开发中～',
						icon: 'success'
					});
				}
			},

			// 点击身份修改时打开弹窗，初始化当前选项
			async onEditIdentityClick() {
				this.editBindType = String(this.userInfo.bindType || '0');
				this.editUserName = this.userInfo.userName || '';
				this.showEditIdentityModal = true;
			},

			// 提交身份修改
			async submitIdentity() {
				// if (this.editBindType === this.userInfo.bindType) {
				// 	uni.showToast({
				// 		title: '身份未修改',
				// 		icon: 'none'
				// 	});
				// 	this.showEditIdentityModal = false;
				// 	return;
				// }

				try {
					// 这里调用你的接口，更新用户身份
					const res = await myRequest.updateUserIdentity({
						id: this.userInfo.id,
						bindType: this.editBindType,
						userName: this.editUserName,
					});

					if (res.data.code === 200) {
						uni.showToast({
							title: '身份更新成功',
							icon: 'success'
						});
						this.userInfo.bindType = this.editBindType;
						this.userInfo.userName = this.editUserName;
						this.showEditIdentityModal = false;
						// 清除缓存
						uni.clearStorageSync();
					} else {
						uni.showToast({
							title: res.data.message || '更新失败',
							icon: 'fail'
						});
					}
				} catch (err) {
					uni.showToast({
						title: '请求出错',
						icon: 'none'
					});
				}
			},


			// 选择模板并下载
			downloadTemplate() {
			    const templates = [
			        {
			            name: 'Word',
			            fileType: 2,
			            ext: 'docx', // 扩展名
			            url: 'https://chouba.top/sign/note/template/download?fileType=2'
			        },
			        {
			            name: 'PDF',
			            fileType: 3,
			            ext: 'pdf',
			            url: 'https://chouba.top/sign/note/template/download?fileType=3'
			        }
			    ];
			
			    uni.showActionSheet({
			        title: '请选择笔记模版',
			        itemList: templates.map(t => t.name),
			        success: (res) => {
			            const selected = templates[res.tapIndex];
			            uni.showModal({
			                title: '下载确认',
			                content: `确定要下载 ${selected.name} 吗？`,
			                success: (modalRes) => {
			                    if (modalRes.confirm) {
			                        // 把扩展名传过去
			                        this.startDownload(selected.url, selected.ext);
			                    }
			                }
			            });
			        }
			    });
			},
			
			// 执行下载
			startDownload(fileUrl, fileExt) {
			    uni.showLoading({ title: '下载中...' });
			
			    uni.downloadFile({
			        url: fileUrl,
			        success: (res) => {
			            if (res.statusCode === 200 || res.data.code === 200) {
			                const fsm = uni.getFileSystemManager();
			                const fileName = `题够笔记上传模版.${fileExt}`; // 固定文件名
			                const filePath = `${wx.env.USER_DATA_PATH}/${fileName}`;
			
			                fsm.writeFile({
			                    filePath,
			                    data: res.tempFilePath ? uni.getFileSystemManager().readFileSync(res.tempFilePath) : res.data,
			                    encoding: 'binary',
			                    success: () => {
			                        uni.hideLoading();
			                        uni.openDocument({
			                            filePath,
			                            fileType: fileExt,
			                            success: () => {
			                                uni.showToast({ title: '下载完成!', icon: 'success' });
			                            },
			                            fail: () => {
			                                uni.showToast({ title: '打开失败', icon: 'none' });
			                            }
			                        });
			                    },
			                    fail: () => {
			                        uni.hideLoading();
			                        uni.showToast({ title: '保存失败', icon: 'none' });
			                    }
			                });
			            } else {
			                uni.hideLoading();
			                uni.showToast({ title: '下载失败', icon: 'fail' });
			            }
			        },
			        fail: () => {
			            uni.hideLoading();
			            uni.showToast({ title: '下载出错', icon: 'none' });
			        }
			    });
			},


			// 自动重新登录
			async autoLogin() {
				try {
					const loginRes = await uni.login({
						provider: 'weixin',
						onlyAuthorize: true
					});
					const jsCode = loginRes.code;

					const res = await loginRequest.loginApi(jsCode);
					if (res.data.code === 200) {
						uni.setStorageSync('token', res.data.data?.token);
						uni.setStorageSync('userId', res.data.data?.userId);
						uni.setStorageSync('bindCode', res.data.data?.bindCode);
						uni.setStorageSync('bindType', res.data.data?.bindType);
					} else {
						throw new Error(res.data.message || '登录失效，请重新登录');
					}
				} catch (error) {
					uni.showToast({
						title: '登录异常，请重试',
						icon: 'none'
					});
				}
			},


			async loadUserInfo() {
				try {
					const userId = uni.getStorageSync('userId');
					if (userId === null) {
						await this.autoLogin()
					}
					const res = await myRequest.getUserInfo(userId, {});
					this.userInfo = res.data.data || {};
				} catch (err) {
					console.error('获取用户信息失败', err);
				}
			},

			async refreshUserData() {
				await this.loadUserInfo();
				this.balanceList = [{
						value: this.userInfo.drawCurrency || 0,
						label: '抽币'
					},
					{
						value: this.userInfo.point || 0,
						label: '积分'
					},
					{
						value: this.userInfo.medal || 0,
						label: '勋章'
					}
				];
			},
		},

	};
</script>

<style lang="scss" scoped>
	.user {
		padding: 28rpx;
		display: flex;
		align-items: center;

		.avatar-wrap {
			width: 84px;
			height: 84px;
			background: #d8d8d8;
			border-radius: 50%;
			overflow: hidden;

			.avatar {
				width: 100%;
				height: 100%;
			}
		}

		.user-info {
			margin-left: 20rpx;

			.oneline {
				display: flex;
				align-items: center;

				.username {
					font-weight: 600;
					font-size: 40rpx;
					color: #3d3d3d;
				}

				.shenfen {
					font-size: 20rpx;
					color: #939393;
					margin-left: 20rpx;
				}
			}

			.userid,
			.user-days {
				font-size: 20rpx;
				color: #939393;
				margin-top: 10rpx;
			}

			.username {
				max-width: 50vw;
			}
		}
	}

	.balance-wrap {
		margin-top: 30rpx;
		display: flex;
		justify-content: space-between;

		.balance-item {
			flex: 1;
			display: flex;
			flex-direction: column;
			align-items: center;

			.number {
				font-size: 40rpx;
			}

			.text {
				margin-top: 10rpx;
				font-size: 28rpx;
			}
		}
	}

	.notice-wrap {
		width: 672rpx;
		height: 160rpx;
		border-radius: 24rpx;
		background: linear-gradient(-270deg, #494748 0%, #292733 100%);
		border: 2rpx solid #ffffff;
		margin: 40rpx auto;
		display: flex;
		align-items: center;
		justify-content: center;
		color: #f4b243;
		font-size: 30rpx;
	}

	.grid-wrap {
		display: flex;
		flex-wrap: wrap;

		.grid-item {
			width: 25%;
			margin-bottom: 40rpx;
			display: flex;
			flex-direction: column;
			align-items: center;

			.img {
				width: 70rpx;
				height: 70rpx;
			}

			.name {
				font-size: 32rpx;
				color: #3d3d3d;
				margin-top: 25rpx;
			}
		}
	}

	.modal-body {
		padding: 24rpx;
	}

	.form-item {
		margin-bottom: 30rpx;
		display: flex;
		flex-direction: column;
	}

	.label {
		font-size: 28rpx;
		color: #333;
		margin-bottom: 12rpx;
	}

	.input {
		height: 44rpx;
		padding: 0 12rpx;
		font-size: 28rpx;
		border: 1rpx solid #ddd;
		border-radius: 8rpx;
		outline: none;
	}

	.radio-group {
		display: flex;
		flex-direction: row;
		gap: 30rpx;
	}

	.radio-label {
		display: flex;
		align-items: center;
		font-size: 28rpx;
		color: #444;
	}

	.radio-label text {
		margin-left: 8rpx;
	}

	.modal-footer {
		display: flex;
		justify-content: flex-end;
		gap: 20rpx;
	}

	.btn {
		padding: 10rpx 30rpx;
		border-radius: 8rpx;
		font-size: 28rpx;
		cursor: pointer;
	}

	.btn.cancel {
		background-color: #eee;
		color: #666;
	}

	.btn.confirm {
		background-color: #d9822b;
		color: #fff;
	}
</style>